import axios from "axios";
import useAppStore from "@/store/appStore";
const http = axios.create({
  baseURL: "/",
  timeout: 10000,
});

// 请求拦截器（添加全局配置）
http.interceptors.request.use(
  (config) => {
    const { guid, appId } = useAppStore.getState().settings;
    // const token = localStorage.getItem("token");
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`;
    // }
    config.headers.gu = "42082a960e504f82b721bb367f9ebeea";
    config.headers.ai = appId;
    config.headers["Content-type"] = "application/json;charset=UTF-8";
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器（统一处理错误）
http.interceptors.response.use(
  (response) => {
    const {
      headers: { at = "", rd = "", ti = "" },
    } = response;
    const currentToken = useAppStore.getState().settings.token;
    const newToken =
      at && rd
        ? JSON.stringify({
            at,
            rd,
            ti,
          })
        : "";
    // 当 at rd 变化时再更新 token
    if (newToken && newToken !== currentToken) {
      useAppStore.getState().updateSettings({
        ti,
        rd,
        at,
        token: newToken,
      });
    }
    return response.data; // 直接返回业务数据
  },
  (error) => {
    if (error.response?.status === 401) {
      // 处理未授权逻辑（如跳转登录页）
    }
    return Promise.reject(error);
  }
);

export default http;
